import java.util.Arrays;

public class MyPriorityQueue {
    private int[] elem;
    private int usedSize;

    private static final int defaultCapacity = 11;


    public MyPriorityQueue() {
        elem = new int[defaultCapacity];
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {
        for(int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
        for(int parent = (elem.length-2) / 2; parent >= 0; parent-- ) {
            shiftDown(parent, usedSize);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int parent = root;
        int child = root * 2 + 1;
        while(child < len) {
            if(child + 1 < len && elem[child] < elem[child+1]) {
                child = child + 1;
            }
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                parent = child;
                child = parent * 2 + 1;
            }else {
                break;
            }
        }
    }
    private void swap(int x, int y) {
        int tmp = elem[x];
        elem[x] = elem[y];
        elem[y] = tmp;
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(usedSize > elem.length) return;

        elem[usedSize++] = val;
        shiftUp(usedSize - 1);
    }

    private void shiftUp(int child) {
        int parent = (child -1) / 2;
        while(child > 0) {
            if(child + 1 < usedSize && elem[child+1] > elem[child]) {
                child++;
            }
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        swap(0, usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);

    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(this.isEmpty()) return 9999999;
        return elem[0];
    }

    public void display() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }
}
